"""
https://zhuanlan.zhihu.com/p/107683577
https://www.jianshu.com/p/d76e98e43c00
"""
import os
from PIL import Image
from removebg import RemoveBg


def image_matting(old_image_path, new_image_path, api_key, color):
    # API KEY获取官方网站：https://www.remove.bg/zh/api
    rmbg = RemoveBg(api_key, "error.log")
    rmbg.remove_background_from_img_file(old_image_path)

    parent_path = os.path.dirname(old_image_path)
    # 如果路径为空，则区当前路径
    if parent_path == "":
        parent_path = "."
    old_image_name = os.path.split(old_image_path)[-1]
    no_bg_image_name = old_image_name + "_no_bg.png"
    if no_bg_image_name in os.listdir(parent_path):
        no_bg_image_path = parent_path + "/" + no_bg_image_name
        no_bg_image = Image.open(no_bg_image_path)
        x, y = no_bg_image.size
        try:
            new_image = Image.new('RGB', no_bg_image.size, color=color)
            new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
            # 在下面生成，下面转换的像素高
            # new_image.save(new_image_path)
        except Exception as e:
            print("Excepetion: ", e)
            print("image matting except")
    else:
        print("image matting fail")


image_matting("baidi.jpg", "baidi_out.jpg", "CAbrb37YK8hNBt14NCTLKjKs", "red")

print("转换成功")

# 也可以在以上处理后，使用一下代码生成图片, 像素高！！！
out_path = "../no_upload/out.png"
# 要替换的背景颜色
color = "red"
# 加上背景颜色
no_bg_image = Image.open("baidi.jpg_no_bg.png")
x, y = no_bg_image.size
new_image = Image.new('RGBA', no_bg_image.size, color=color)
new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
new_image.save(out_path)
